library(tidyverse) # for data cleaning and plotting
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.0 ──
## ✓ ggplot2 3.3.2 ✓ purrr 0.3.4
## ✓ tibble 3.0.4 ✓ dplyr 1.0.2
## ✓ tidyr 1.1.2 ✓ stringr 1.4.0
## ✓ readr 1.4.0 ✓ forcats 0.5.0
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## x dplyr::filter() masks stats::filter()
## x dplyr::lag() masks stats::lag()
library(googlesheets4) # for reading googlesheet data
library(lubridate) # for date manipulation
##
## Attaching package: 'lubridate'
## The following objects are masked from 'package:base':
##
## date, intersect, setdiff, union
library(openintro) # for the abbr2state() function
## Loading required package: airports
## Loading required package: cherryblossom
## Loading required package: usdata
library(palmerpenguins)# for Palmer penguin data
library(maps) # for map data
##
## Attaching package: 'maps'
## The following object is masked from 'package:purrr':
##
## map
library(ggmap) # for mapping points on maps
## Google's Terms of Service: https://cloud.google.com/maps-platform/terms/.
## Please cite ggmap if you use it! See citation("ggmap") for details.
library(gplots) # for col2hex() function
##
## Attaching package: 'gplots'
## The following object is masked from 'package:stats':
##
## lowess
library(RColorBrewer) # for color palettes
library(sf) # for working with spatial data
## Linking to GEOS 3.8.1, GDAL 3.1.1, PROJ 6.3.1
library(leaflet) # for highly customizable mapping
library(carData) # for Minneapolis police stops data
library(ggthemes) # for more themes (including theme_map())
gs4_deauth() # To not have to authorize each time you knit.
theme_set(theme_minimal())
# Starbucks locations
Starbucks <- read_csv("https://www.macalester.edu/~ajohns24/Data/Starbucks.csv")
##
## ── Column specification ────────────────────────────────────────────────────────
## cols(
## Brand = col_character(),
## `Store Number` = col_character(),
## `Store Name` = col_character(),
## `Ownership Type` = col_character(),
## `Street Address` = col_character(),
## City = col_character(),
## `State/Province` = col_character(),
## Country = col_character(),
## Postcode = col_character(),
## `Phone Number` = col_character(),
## Timezone = col_character(),
## Longitude = col_double(),
## Latitude = col_double()
## )
starbucks_us_by_state <- Starbucks %>%
filter(Country == "US") %>%
count(`State/Province`) %>%
mutate(state_name = str_to_lower(abbr2state(`State/Province`)))
# Lisa's favorite St. Paul places - example for you to create your own data
favorite_stp_by_lisa <- tibble(
place = c("Home", "Macalester College", "Adams Spanish Immersion",
"Spirit Gymnastics", "Bama & Bapa", "Now Bikes",
"Dance Spectrum", "Pizza Luce", "Brunson's"),
long = c(-93.1405743, -93.1712321, -93.1451796,
-93.1650563, -93.1542883, -93.1696608,
-93.1393172, -93.1524256, -93.0753863),
lat = c(44.950576, 44.9378965, 44.9237914,
44.9654609, 44.9295072, 44.9436813,
44.9399922, 44.9468848, 44.9700727)
)
#COVID-19 data from the New York Times
covid19 <- read_csv("https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-states.csv")
##
## ── Column specification ────────────────────────────────────────────────────────
## cols(
## date = col_date(format = ""),
## state = col_character(),
## fips = col_character(),
## cases = col_double(),
## deaths = col_double()
## )
If you were not able to get set up on GitHub last week, go here and get set up first. Then, do the following (if you get stuck on a step, don’t worry, I will help! You can always get started on the homework and we can figure out the GitHub piece later):
keep_md: TRUE in the YAML heading. The .md file is a markdown (NOT R Markdown) file that is an interim step to creating the html file. They are displayed fairly nicely in GitHub, so we want to keep it and look at it there. Click the boxes next to these two files, commit changes (remember to include a commit message), and push them (green up arrow).Put your name at the top of the document.
For ALL graphs, you should include appropriate labels.
Feel free to change the default theme, which I currently have set to theme_minimal().
Use good coding practice. Read the short sections on good code with pipes and ggplot2. This is part of your grade!
When you are finished with ALL the exercises, uncomment the options at the top so your document looks nicer. Don’t do it before then, or else you might miss some important warnings and messages.
These exercises will reiterate what you learned in the “Mapping data with R” tutorial. If you haven’t gone through the tutorial yet, you should do that first.
ggmap)Starbucks locations to a world map. Add an aesthetic to the world map that sets the color of the points according to the ownership type. What, if anything, can you deduce from this visualization?world <- get_stamenmap(
bbox = c(left = -180, bottom = -57, right = 179, top = 82.1),
maptype = "terrain",
zoom = 2)
## Source : http://tile.stamen.com/terrain/2/0/0.png
## Source : http://tile.stamen.com/terrain/2/1/0.png
## Source : http://tile.stamen.com/terrain/2/2/0.png
## Source : http://tile.stamen.com/terrain/2/3/0.png
## Source : http://tile.stamen.com/terrain/2/0/1.png
## Source : http://tile.stamen.com/terrain/2/1/1.png
## Source : http://tile.stamen.com/terrain/2/2/1.png
## Source : http://tile.stamen.com/terrain/2/3/1.png
## Source : http://tile.stamen.com/terrain/2/0/2.png
## Source : http://tile.stamen.com/terrain/2/1/2.png
## Source : http://tile.stamen.com/terrain/2/2/2.png
## Source : http://tile.stamen.com/terrain/2/3/2.png
# Plot the points on the map
ggmap(world) + # creates the map "background"
geom_point(data = Starbucks,
aes(x = Longitude, y = Latitude, color = `Ownership Type`),
alpha = .3,
size = .1) +
scale_color_viridis_d() +
theme_map()
## Warning: Removed 1 rows containing missing values (geom_point).
Twin_Cities_Starbucks <- get_stamenmap(
bbox = c(left = -93.3100, bottom = 44.8818, right = -92.9482, top = 45.0453),
maptype = "terrain",
zoom = 12)
## Source : http://tile.stamen.com/terrain/12/986/1472.png
## Source : http://tile.stamen.com/terrain/12/987/1472.png
## Source : http://tile.stamen.com/terrain/12/988/1472.png
## Source : http://tile.stamen.com/terrain/12/989/1472.png
## Source : http://tile.stamen.com/terrain/12/990/1472.png
## Source : http://tile.stamen.com/terrain/12/986/1473.png
## Source : http://tile.stamen.com/terrain/12/987/1473.png
## Source : http://tile.stamen.com/terrain/12/988/1473.png
## Source : http://tile.stamen.com/terrain/12/989/1473.png
## Source : http://tile.stamen.com/terrain/12/990/1473.png
## Source : http://tile.stamen.com/terrain/12/986/1474.png
## Source : http://tile.stamen.com/terrain/12/987/1474.png
## Source : http://tile.stamen.com/terrain/12/988/1474.png
## Source : http://tile.stamen.com/terrain/12/989/1474.png
## Source : http://tile.stamen.com/terrain/12/990/1474.png
## Source : http://tile.stamen.com/terrain/12/986/1475.png
## Source : http://tile.stamen.com/terrain/12/987/1475.png
## Source : http://tile.stamen.com/terrain/12/988/1475.png
## Source : http://tile.stamen.com/terrain/12/989/1475.png
## Source : http://tile.stamen.com/terrain/12/990/1475.png
ggmap(Twin_Cities_Starbucks) + # creates the map "background"
geom_point(data = Starbucks,
aes(x = Longitude, y = Latitude),
alpha = .3,
color = "darkred",
size = 5) +
theme_map()
## Warning: Removed 25560 rows containing missing values (geom_point).
Decreasing the zoom makes the map less detailed overall. You end up seeing less specific locations, they all blur together.
get_stamenmap() in help and look at maptype). Include a map with one of the other map types.Twin_Cities_Starbucks <- get_stamenmap(
bbox = c(left = -93.3100, bottom = 44.8818, right = -92.9482, top = 45.0453),
maptype = "toner",
zoom = 12)
## Source : http://tile.stamen.com/toner/12/986/1472.png
## Source : http://tile.stamen.com/toner/12/987/1472.png
## Source : http://tile.stamen.com/toner/12/988/1472.png
## Source : http://tile.stamen.com/toner/12/989/1472.png
## Source : http://tile.stamen.com/toner/12/990/1472.png
## Source : http://tile.stamen.com/toner/12/986/1473.png
## Source : http://tile.stamen.com/toner/12/987/1473.png
## Source : http://tile.stamen.com/toner/12/988/1473.png
## Source : http://tile.stamen.com/toner/12/989/1473.png
## Source : http://tile.stamen.com/toner/12/990/1473.png
## Source : http://tile.stamen.com/toner/12/986/1474.png
## Source : http://tile.stamen.com/toner/12/987/1474.png
## Source : http://tile.stamen.com/toner/12/988/1474.png
## Source : http://tile.stamen.com/toner/12/989/1474.png
## Source : http://tile.stamen.com/toner/12/990/1474.png
## Source : http://tile.stamen.com/toner/12/986/1475.png
## Source : http://tile.stamen.com/toner/12/987/1475.png
## Source : http://tile.stamen.com/toner/12/988/1475.png
## Source : http://tile.stamen.com/toner/12/989/1475.png
## Source : http://tile.stamen.com/toner/12/990/1475.png
ggmap(Twin_Cities_Starbucks) + # creates the map "background"
geom_point(data = Starbucks,
aes(x = Longitude, y = Latitude),
alpha = .3,
color = "darkred",
size = 5) +
theme_map()
## Warning: Removed 25560 rows containing missing values (geom_point).
annotate() function (see ggplot2 cheatsheet).Twin_Cities_Starbucks <- get_stamenmap(
bbox = c(left = -93.3100, bottom = 44.8818, right = -92.9482, top = 45.0453),
maptype = "toner",
zoom = 12)
ggmap(Twin_Cities_Starbucks) +
geom_point(data = Starbucks,
aes(x = Longitude, y = Latitude),
alpha = .3,
color = "darkred",
size = 5) +
annotate("text", x= -93.1696, y=44.944, label = "Macalester College", color = "blue", size = 3) +
annotate("point", x= -93.1696, y=44.9386, label = "Macalester College", color = "blue", size = 3) +
labs(x = 'Longitude', y = 'Latitude') + ggtitle('Macalester College')
## Warning: Ignoring unknown parameters: label
## Warning: Removed 25560 rows containing missing values (geom_point).
geom_map())The example I showed in the tutorial did not account for population of each state in the map. In the code below, a new variable is created, starbucks_per_10000, that gives the number of Starbucks per 10,000 people. It is in the starbucks_with_2018_pop_est dataset.
census_pop_est_2018 <- read_csv("https://www.dropbox.com/s/6txwv3b4ng7pepe/us_census_2018_state_pop_est.csv?dl=1") %>%
separate(state, into = c("dot","state"), extra = "merge") %>%
select(-dot) %>%
mutate(state = str_to_lower(state))
##
## ── Column specification ────────────────────────────────────────────────────────
## cols(
## state = col_character(),
## est_pop_2018 = col_double()
## )
starbucks_with_2018_pop_est <-
starbucks_us_by_state %>%
left_join(census_pop_est_2018,
by = c("state_name" = "state")) %>%
mutate(starbucks_per_10000 = (n/est_pop_2018)*10000)
dplyr review: Look through the code above and describe what each line of code does.The “separate” command splits up the data by whichever specified character, with this one, it separates by dots and state. The “select” function chooses to extract that specific variable as columns to the data set. The “mutate” function after that is used to add a new variable, specifically one that adds the states in all lowercase letters. The next part of code joins the census dataset with the starbucks population dataset by state name. The next line creates a new variable that gives the number of Starbucks stores per 10,000 people.
census_pop_est_2018 <- read_csv("https://www.dropbox.com/s/6txwv3b4ng7pepe/us_census_2018_state_pop_est.csv?dl=1") %>%
separate(state, into = c("dot","state"), extra = "merge") %>%
select(-dot) %>%
mutate(state = str_to_lower(state))
##
## ── Column specification ────────────────────────────────────────────────────────
## cols(
## state = col_character(),
## est_pop_2018 = col_double()
## )
states_map <- map_data("state")
starbucks_with_2018_pop_est <-
starbucks_us_by_state %>%
left_join(census_pop_est_2018,
by = c("state_name" = "state")) %>%
mutate(starbucks_per_10000 = (n/est_pop_2018)*10000)
starbucks_with_2018_pop_est %>%
ggplot() +
geom_map(map = states_map,
aes(map_id = state_name,
fill = starbucks_per_10000)) +
#This assures the map looks decently nice:
expand_limits(x = states_map$long, y = states_map$lat) +
labs(title = "Starbucks Per 10,000 People in the U.S") +
theme_map()
### A few of your favorite things (
leaflet)
tibble() function that has 10-15 rows of your favorite places. The columns will be the name of the location, the latitude, the longitude, and a column that indicates if it is in your top 3 favorite locations or not. For an example of how to use tibble(), look at the favorite_stp_by_lisa I created in the data R code chunk at the beginning.favorite_places_by_mary <- tibble(
place = c("Home", "Macalester College", "Moody Beach",
"Grand Canyon", "Pike and Rose", "The Spooky House"),
long = c(-77.0550, -93.1712321, -70.5840,
-112.1393, -77.1181, -77.0732),
lat = c(39.0261, 44.9378965, 43.2742,
36.0544, 39.0491, 39.0245),
top_three = c("yes", "no", "yes", "no", "no", "yes")
)
leaflet map that uses circles to indicate your favorite places. Label them with the name of the place. Choose the base map you like best. Color your 3 favorite places differently than the ones that are not in your top 3 (HINT: colorFactor()). Add a legend that explains what the colors mean.pal <- colorFactor("viridis",
domain = favorite_places_by_mary$top_three)
leaflet(data = favorite_places_by_mary) %>%
addProviderTiles(providers$Stamen.Watercolor) %>%
addCircles(lng = ~long,
lat = ~lat,
label = ~place,
color = ~pal(top_three),
weight = 10,
opacity = 1) %>%
addLegend("topleft",
pal = pal,
values = ~top_three)
leaflet(data = favorite_places_by_mary) %>%
addProviderTiles(providers$CartoDB.DarkMatter) %>%
addCircles(lng = ~long,
lat = ~lat,
label = ~place,
weight = 10,
opacity = 1,
color = col2hex("darkgreen")) %>%
addPolylines(lng = ~long,
lat = ~lat,
color = col2hex("darkgreen"))
* If there are other variables you want to add that could enhance your plot, do that now.
This section will revisit some datasets we have used previously and bring in a mapping component.
The data come from Washington, DC and cover the last quarter of 2014.
Two data tables are available:
Trips contains records of individual rentalsStations gives the locations of the bike rental stationsHere is the code to read in the data. We do this a little differently than usualy, which is why it is included here rather than at the top of this file. To avoid repeatedly re-reading the files, start the data import chunk with {r cache = TRUE} rather than the usual {r}. This code reads in the large dataset right away.
data_site <-
"https://www.macalester.edu/~dshuman1/data/112/2014-Q4-Trips-History-Data.rds"
Trips <- readRDS(gzcon(url(data_site)))
Stations<-read_csv("http://www.macalester.edu/~dshuman1/data/112/DC-Stations.csv")
##
## ── Column specification ────────────────────────────────────────────────────────
## cols(
## name = col_character(),
## lat = col_double(),
## long = col_double(),
## nbBikes = col_double(),
## nbEmptyDocks = col_double()
## )
Stations to make a visualization of the total number of departures from each station in the Trips data. Use either color or size to show the variation in number of departures. This time, plot the points on top of a map. Use any of the mapping tools you’d like.Stations %>%
summarize(min(lat),
max(lat),
min(long),
max(long))
dc_map <- get_stamenmap(
bbox = c(left = -77.2025 , bottom = 38.80111, right = -76.93186, top = 39.12351),
maptype = "terrain",
zoom = 11
)
## Source : http://tile.stamen.com/terrain/11/584/781.png
## Source : http://tile.stamen.com/terrain/11/585/781.png
## Source : http://tile.stamen.com/terrain/11/586/781.png
## Source : http://tile.stamen.com/terrain/11/584/782.png
## Source : http://tile.stamen.com/terrain/11/585/782.png
## Source : http://tile.stamen.com/terrain/11/586/782.png
## Source : http://tile.stamen.com/terrain/11/584/783.png
## Source : http://tile.stamen.com/terrain/11/585/783.png
## Source : http://tile.stamen.com/terrain/11/586/783.png
## Source : http://tile.stamen.com/terrain/11/584/784.png
## Source : http://tile.stamen.com/terrain/11/585/784.png
## Source : http://tile.stamen.com/terrain/11/586/784.png
departure_by_station <- Trips %>%
left_join(Stations, by = c("sstation" = "name")) %>%
group_by(lat, long) %>%
summarize(n = n(),
prop_casual = mean(client == "Casual") #used in next problem
)
## `summarise()` regrouping output by 'lat' (override with `.groups` argument)
ggmap(dc_map) +
geom_point(data = departure_by_station,
aes(x = long,
y = lat,
color = n),
alpha=.8,
shape = 17) +
scale_color_viridis_c() +
theme_map() +
theme(legend.background = element_blank())
## Warning: Removed 3 rows containing missing values (geom_point).
ggmap(dc_map) +
geom_point(data = departure_by_station,
aes(x = long,
y = lat,
color = prop_casual),
alpha=.8,
shape = 17) +
scale_color_viridis_c() +
theme_map() +
labs(title = "Areas With Stations with a Higher %
of Departures by Casual Users by Latitude and Longitude",
x = "longitude",
y = "latitude") +
theme(legend.background = element_blank())
## Warning: Removed 3 rows containing missing values (geom_point).
The following exercises will use the COVID-19 data from the NYT.
This map is slightly misleading because it seems like big states like Texas and California are doing considerably worse in terms of Covid-19 cases overall. The map does not take into account population density.
covid19 %>%
mutate(state = str_to_lower(state)) %>%
group_by(state) %>%
summarize(total = max(cases)) %>%
left_join(census_pop_est_2018,
by = c("state" = "state")) %>%
ggplot() +
geom_map(map = states_map,
aes(map_id = state,
fill = total)) +
#This assures the map looks decently nice:
expand_limits(x = states_map$long, y = states_map$lat) +
theme_map() +
theme(legend.position = "right",
legend.key.size = unit(1.5, "line")) +
labs(title = "COVID-19 Cases per Capita",
caption = "Mary McDonnell",
fill = "Cummulative Covid-19 Cases")
## `summarise()` ungrouping output (override with `.groups` argument)
covid19 %>%
mutate(state = str_to_lower(state)) %>%
group_by(state) %>%
summarize(total = max(cases)) %>%
left_join(census_pop_est_2018,
by = c("state" = "state")) %>%
mutate(per_cap = (total/est_pop_2018)*10000) %>%
ggplot() +
geom_map(map = states_map,
aes(map_id = state,
fill = per_cap)) +
#This assures the map looks decently nice:
expand_limits(x = states_map$long, y = states_map$lat) +
theme_map() +
theme(legend.position = "right",
legend.key.size = unit(1.5, "line")) +
labs(title = "COVID-19 Cases per Capita",
caption = "By Mary McDonnell",
fill = "Cases per 10,000")
## `summarise()` ungrouping output (override with `.groups` argument)
These exercises use the datasets MplsStops and MplsDemo from the carData library. Search for them in Help to find out more information.
MplsStops dataset to find out how many stops there were for each neighborhood and the proportion of stops that were for a suspicious vehicle or person. Sort the results from most to least number of stops. Save this as a dataset called mpls_suspicious and display the table.mpls_suspicious <-
MplsStops %>%
group_by(neighborhood) %>%
summarize(total_stops = n(),
prop_suspicious = sum(problem == "suspicious")/ total_stops)
## `summarise()` ungrouping output (override with `.groups` argument)
leaflet map and the MplsStops dataset to display each of the stops on a map as a small point. Color the points differently depending on whether they were for suspicious vehicle/person or a traffic stop (the problem variable). HINTS: use addCircleMarkers, set stroke = FAlSE, use colorFactor() to create a palette.pal <- colorFactor("viridis",
domain = MplsStops$problem)
leaflet(data = MplsStops) %>%
addProviderTiles(providers$Stamen.Terrain) %>%
addCircles(lng = ~long,
lat = ~lat,
label = ~neighborhood,
color = ~pal(problem),
weight = 2,
opacity = 1) %>%
addLegend("topleft",
pal = pal,
values = ~problem)
eval=FALSE. Although it looks like it only links to the .sph file, you need the entire folder of files to create the mpls_nbhd data set. These data contain information about the geometries of the Minneapolis neighborhoods. Using the mpls_nbhd dataset as the base file, join the mpls_suspicious and MplsDemo datasets to it by neighborhood (careful, they are named different things in the different files). Call this new dataset mpls_all.mpls_nbhd <- st_read("Minneapolis_Neighborhoods/Minneapolis_Neighborhoods.shp", quiet = TRUE)
mpls_all <- mpls_nbhd %>%
left_join(MplsDemo,
by = c("BDNAME" = "neighborhood")) %>%
left_join(mpls_suspicious,
by = c("BDNAME" = "neighborhood")) %>%
left_join(MplsStops,
by = c("BDNAME" = "neighborhood"))
leaflet to create a map from the mpls_all data that colors the neighborhoods by prop_suspicious. Display the neighborhood name as you scroll over it. Describe what you observe in the map.I notice that most of the suspicious stops occurred in southeast neighborhoods. The legend shows that lighter shades indicate a higher proportion of “suspicious” stops. There are also concentrations of “suspicious” stops in northwest and (to some extent) central neighborhoods, but the biggest concentration is in the southeast I also notice that in the Northeast neighborhoods, there is a high concentration of non-suspicious stops. These neighborhoods are also typically wealthier and whiter, indicating the poorer and Black neighborhoods are stopped at greater rates according to level of suspicion.
pal <- colorFactor("viridis",
domain = mpls_all$prop_suspicious)
leaflet(data = mpls_all) %>%
addProviderTiles(providers$Stamen.Terrain) %>%
addCircles(lng = ~long,
lat = ~lat,
label = ~BDNAME,
color = ~pal(prop_suspicious),
weight = 1,
opacity = 1) %>%
addLegend("topleft",
pal = pal,
values = ~prop_suspicious)
## Warning in validateCoords(lng, lat, funcName): Data contains 1 rows with either
## missing or invalid lat/lon values and will be ignored
leaflet to create a map of your own choosing. Come up with a question you want to try to answer and use the map to help answer that question. Describe what your map shows.This map depicts the poverty concentration in conjunction with suspicious and traffic stops. It shows that generally, places with higher poverty concentrations have more suspicious vs. traffic stops.
pal <- colorFactor("viridis",
domain = mpls_all$poverty)
leaflet(data = mpls_all) %>%
addProviderTiles(providers$Stamen.Terrain) %>%
addCircles(lng = ~long,
lat = ~lat,
label = ~problem,
color = ~pal(poverty),
weight = 1,
opacity = 1) %>%
addLegend("topleft",
pal = pal,
values = ~poverty)
## Warning in validateCoords(lng, lat, funcName): Data contains 1 rows with either
## missing or invalid lat/lon values and will be ignored
## GitHub link
DID YOU REMEMBER TO UNCOMMENT THE OPTIONS AT THE TOP?